/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import calculator.Calculator;
import calculator.CalculatorFactory;
import calculator.CrowflightCalculator;
import calculator.DistanceTableCalculator;
import calculator.ZeroCalculator;
import hibernate.entityes.City;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import result.ResultCalculation;

/**
 *
 * @author eleven
 */
public class CalculateAction implements Action {

    @Override
    public String perform(HttpServletRequest request, HttpServletResponse response) {
        try {
            String type = request.getParameter("typecalculation");
            String fromCity = request.getParameter("fromcity");
            String toCity = request.getParameter("tocity");

            LinkedList<ResultCalculation> results = new LinkedList<ResultCalculation>();
            List<Calculator> calculators = new LinkedList<Calculator>();

            if (type.equals("All Types")) {
                calculators.add(new CrowflightCalculator());
                calculators.add(new DistanceTableCalculator());
                calculators.add(new ZeroCalculator());
            } else {
                calculators.add(new CalculatorFactory(type).getCalculator());
            }
            
            for (Iterator i = calculators.iterator(); i.hasNext();){
                Calculator calc = (Calculator)i.next();
                results.add(calc.calculate(fromCity, toCity));
            }
            request.getSession().setAttribute("results", results);
            response.sendRedirect(request.getContextPath() + "/result.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}